package com.yupi.picturebackend.api.imageSearch.sub;

import cn.hutool.core.util.ObjUtil;
import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import com.yupi.picturebackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取图片地址列表接口的api
 */
@Slf4j
public class GetImageFirstUrlApi {
    public static String getImageFirstUrl(String url){
        try {
            //用Jsoup连接该地址并获取页面文档
            Document document = Jsoup.connect(url).timeout(10000).get();
            //获取页面元素
            Elements scriptElements = document.getElementsByTag("script");
            ThrowUtils.throwIf(ObjUtil.isEmpty(scriptElements), ErrorCode.OPERATION_ERROR, "获取页面元素失败");
            //遍历元素，获取firstUrl的脚本内容
            for (Element script : scriptElements) {
                String scriptContent = script.html();
                if (scriptContent.contains("\"firstUrl\"")) {
                    // 正则表达式提取 firstUrl 的值
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    Matcher matcher = pattern.matcher(scriptContent);
                    if (matcher.find()) {
                        String firstUrl = matcher.group(1);
                        // 处理转义字符
                        firstUrl = firstUrl.replace("\\/", "/");
                        return firstUrl;
                    }
                }
            }
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未找到url地址");
        }catch (Exception e) {
            log.error("搜索失败",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"搜索失败");
        }
    }
    public static void main(String[] args) {
        // 请求目标 URL
        String url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=1072394726557903548&sign=12609e97cd54acd88139901743497229&tpl_from=pc";
        String imageFirstUrl = getImageFirstUrl(url);
        System.out.println("搜索成功，结果 URL：" + imageFirstUrl);
    }
}
